<?php

namespace Joy\OAuth\Command;

use Closure;
use Joy\OAuth\Helper\Str;

trait EnvHelperTrait {
    protected function envFileExists(): bool {
        return file_exists($this->envFile());
    }

    protected function exampleEnvFileExists() {
        return file_exists($this->exampleEnvFile());
    }

    protected function envFile() {
        return root_path() . '.env';
    }

    protected function exampleEnvFile() {
        return root_path() . '.example.env';
    }

    protected function getFileContents(string $filepath): string {
        return file_get_contents($filepath);
    }

    protected function putFileContents(string $filepath, string $data): void {
        file_put_contents($filepath, $data);
    }

    public function updateEnvEntry(string $key, $value, Closure $confirmOnExisting = null): bool
    {
        $filepath = $this->envFile();

        $filecontents = $this->getFileContents($filepath);

        if (false === Str::contains($filecontents, $key)) {
            // create new entry
            $this->putFileContents(
                $filepath,
                "{$key}={$value}". PHP_EOL . PHP_EOL . $filecontents
            );

            return true;
        } else {
            // update existing entry
            $this->putFileContents(
                $filepath,
                preg_replace(
                    "/{$key}=.*/",
                    "{$key}={$value}",
                    $filecontents
                )
            );

            return true;
        }

        return false;
    }
}